<?php

ini_set("display_errors", "On");
error_reporting(E_ALL);

// 引入数据库连接文件
require_once '../../../sql/connection.php';

$addCourseNumber = $_POST['addCourseNumber'];
$addCourseName = $_POST['addCourseName'];
$role = $_COOKIE['role'];
$tId = $_COOKIE['adminID'];

// 查询语句
$querySql = "select id, create_time, update_time, course_number, course_name, is_delete from course_info where course_number='$addCourseNumber'";
// 连接数据库，并查询
$result = mysqli_query($GLOBALS['conn'], $querySql);

//echo $result_config;
if (mysqli_num_rows($result) > 0) {
	echo "
<script>
    alert('该课程编号已存在，请重新输入！');
    history.go(-1);
</script>";
} else {
	$now = date('Y-m-d H:i:s', time());
	
	$addSql = "INSERT INTO course_info(create_time, update_time,  course_number,  course_name, is_delete)VALUES ('$now','$now','$addCourseNumber','$addCourseName',0)";
	if (mysqli_query($GLOBALS['conn'], $addSql)) {
		echo "
            <script>
                alert('添加课程成功！');
                // window.location.href=document.referrer;
            </script>
        ";
		// 如果当前用户是教师，自动关联课程
		if ($role == "教师") {
			// 查询新添加的课程 - SQL语句
			$querySql = "select id from course_info where course_number='$addCourseNumber' and course_name = '$addCourseName'";
			// 连接数据库，并查询
			$result = mysqli_query($GLOBALS['conn'], $querySql);
			$courseRow = mysqli_fetch_array($result);
			$connCouID = $courseRow['id'];
			// 关联语句
			$conTcSql = "INSERT INTO `teacher-course` (create_time, update_time, c_ID, t_ID,is_delete) VALUES ('$now', '$now', '$connCouID', '$tId',0)";
			if (mysqli_query($GLOBALS['conn'], $conTcSql)) {
				echo "
            <script>
                alert('与课程关联成功！');
                window.location.href=document.referrer;
            </script>
        ";
			}
		}

	} else {
		echo "
            <script>
                alert('添加失败！');
                history.back();
            </script>
        ";
	}
	
}

